<?php

namespace App\Http\Controllers\Admin;

use App\Model\Cate;
use App\Tool\Admin\GetCate;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CateController extends Controller
{
    //显示分类
    public function index() {
        $res = Cate::all()->toArray();
        $GetCate =  new GetCate();
        $cates = $GetCate->getTree($res);
        return view('admin.cate.cateList', ['cates' => $cates]);
    }

    //添加分类表单
    public function add () {
        $res = Cate::all()->toArray();
        $GetCate = new GetCate();
        $cates = $GetCate->getTree($res);
        return view('admin.cate.cateAdd', ['cates' => $cates]);
    }

    //添加分类操作
    public function addAction (Request $request) {
        $cate_name = $request->get('cate_name');
        $parent_id = $request->get('parent_id');
        $res = Cate::create([
            'cate_name' => $cate_name,
            'parent_id' => $parent_id
        ]);
        if ($res) {
            return redirect('admin/cateList');
        }
    }

    //修改分类表单
    public function edit ($id) {
        $cate = Cate::find($id)->toArray();
        $res = Cate::all()->toArray();
        $GetCate = new GetCate();
        $cates = $GetCate->getTree($res);
        return view('admin.cate.cateEdit', ['cates' => $cates, 'cate' => $cate]);
    }

    //修改分类操作
    public function editAction (Request $request) {
        $id = $request->get('id');
        $cate_name = $request->get('cate_name');
        $parent_id = $request->get('parent_id');
        $res = Cate::find($id)->update([
            'cate_name' => $cate_name,
            'parent_id' => $parent_id
        ]);
        if ($res) {
            return redirect('admin/cateList');
        }
    }

    //删除分类操作
    public function del($id) {
        $cate = Cate::find($id);
        $res = $cate->delete();
        if ($res) {
            return redirect('admin/cateList');
        }
    }
}
